import React, { useEffect, useState } from 'react';
import {
  Table,
  Button,
  Modal,
  Form,
  Input,
  Select,
  Space,
  Card,
  Divider,
  Typography,
  message,
  Cascader,
  DatePicker,
  TreeSelect,
  InputNumber,
  Popconfirm,
} from 'antd';
import {
  SearchOutlined,
  UndoOutlined,
  EditOutlined,
  DeleteOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  SyncOutlined,
  ClockCircleOutlined,
  AuditOutlined,
} from '@ant-design/icons';
import area from '@/components/staticFile/region_options.json';
import product from '@/components/staticFile/product_options.json';
import chinaEconomy from '@/components/staticFile/industry_classification_options.json';
import dayjs from 'dayjs';
import { pageUsers, removeUsers, update, userProgress } from '@/services/apis/companyRegister';
import { useModel } from '@umijs/max';
import CompanyAllInfosPage from './modal';
const { Title, Text } = Typography;
const { Option } = Select;
const { TextArea } = Input;

// 状态选项
const STATUS_OPTIONS = [
  { value: '待%审核', label: '待审核' },
  { value: '审核通过', label: '已通过' },
  { value: '审核不通过', label: '不通过' },
  { value: '审核退回', label: '已退回' },
];

// 根据状态值获取带颜色的显示文本
const getStatusText = (status: string) => {
  switch (status) {
    case 'pending':
      return <Text>待审核</Text>;
    case 'approved':
      return <Text>已通过</Text>;
    case 'rejected':
      return <Text>不通过</Text>;
    case 'returned':
      return <Text>已退回</Text>;
    case 'processing':
      return <Text></Text>;
    default:
      return <Text>{status}</Text>;
  }
};
// 新增：办理进度列表列配置（固定5个字段）
const progressColumns = [
  {
    title: (
      <Space align="center">
        <span>时间</span>
      </Space>
    ),
    dataIndex: 'createdTime',
    key: 'createdTime',
    width: 200,
    align: 'center',
  },
  {
    title: '单位',
    dataIndex: 'departmentName',
    key: 'departmentName',
    width: 200,
    align: 'center',
  },
  {
    title: '环节',
    dataIndex: 'link',
    key: 'link',
    width: 200,
    align: 'center',
  },
  {
    title: '结果',
    dataIndex: "auditStatus",
    key: 'auditStatus',
    width: 200,
    align: 'center',
    // render: (status: string) => getStatusText(status),
  },
  {
    title: '意见',
    dataIndex: 'auditRemark',
    key: 'auditRemark',
    width: 200,
    align: 'center',
    render: (opinion: string) => (
      <Text >{opinion}</Text>
    ),
  },
];

// 获取状态标签（带颜色）
const getStatusTag = (status: string) => {
  switch (status) {
    case 'pending':
      return <Text >待审核</Text>;
    case 'approved':
      return <Text>已通过</Text>;
    case 'rejected':
      return <Text >不通过</Text>;
    case 'in_progress':
      return <Text>进行中</Text>;
    default:
      return <Text>{status}</Text>;
  }
};

const PilotEnterpriseManagement: React.FC = () => {
  // 状态管理：新增进度相关状态
  const [enterprises, setEnterprises] = useState([]);
  const [searchForm] = Form.useForm();
  const [editForm] = Form.useForm();
  const [reviewForm] = Form.useForm();
  const [currentEnterprise, setCurrentEnterprise] = useState<any>(null);
  const { initialState, setInitialState } = useModel('@@initialState');
  const {
    modalProps,
    setModalProps,
  } = useModel("CompanyManager.modal")
  // const [serviceProviders, setServiceProviders] = useState([]);
  const [modalVisible, setModalVisible] = useState({
    edit: false,
    review: false,
    progress: false, // 新增：进度弹窗控制
  });
  const [currentProgressList, setCurrentProgressList] = useState<any[]>([]); // 新增：当前企业的进度数据
  const [pageProps, setPageProps] = useState<{ current: number, pageSize: number, total: number }>({
    current: 1,
    pageSize: 10,
    total: 0
  })

  // ---------------------- 新增：打开进度弹窗逻辑 ----------------------
  const handleProgressOpen = (record: any) => {

    userProgress({ id: record.id }).then(res => {
      const { code, data } = res
      if (code == "0") {
        setCurrentEnterprise(record);
        setCurrentProgressList(data);
      }
    })
    setModalVisible({
      ...modalVisible,
      progress: true,
    });
  };

  // 搜索处理
  const handleSearch = async () => {
    searchUsers({ ...searchForm.getFieldsValue(), current: pageProps.current, size: pageProps.pageSize })
  };

  // 重置搜索
  const handleReset = () => {
    searchForm.resetFields();
    searchUsers({ current: pageProps.current, size: pageProps.pageSize })
  };

  // 删除企业
  const handleDelete = (id: string) => {
    removeUsers({ id }).then(res => {
      const { code } = res
      if (code == "0") {
        //message.success("删除企业用户成功")
        searchUsers({ ...searchForm.getFieldsValue(), current: pageProps.current, size: pageProps.pageSize })
      }
    })
  };

  // 打开编辑弹窗：新增关闭进度弹窗逻辑
  const handleEdit = (record: any, title: string) => {
    setModalProps(prev => ({ ...prev, visible: true, record, title }))
  };

  // 保存编辑
  const handleSaveEdit = async () => {
    try {
      const values = await editForm.validateFields();
      update({ id: (initialState?.currentUser as any).data.id, ...values }).then(res => {
        const { code } = res;
        if (code == "0") {
          setModalVisible({ ...modalVisible, edit: false });
          //message.success('企业信息已更新');
          searchUsers({ ...searchForm.getFieldsValue(), current: pageProps.current, size: pageProps.pageSize })
        }
      })

    } catch (error) {
      // 表单验证失败
      return;
    }
  };

  const searchUsers = (values: any) => {
    pageUsers({
      ...values,
      loginInArea: initialState?.currentUser.data.loginInArea,
      userType: initialState?.currentUser.data.userType,
    }).then(res => {
      const { code, data } = res
      if (code == "0") {
        setEnterprises(data.records)
        setPageProps({
          current: data.current,
          pageSize: data.size,
          total: data.total
        })
        //message.success("请求成功")
      }
    })
  }
  useEffect(() => {
    searchUsers({ current: pageProps.current, size: pageProps.pageSize })
  }, [])
  const usersPageOnchange = (current: any, pageSize: any) => {
    searchUsers({ ...searchForm.getFieldsValue(), current, size: pageSize })
  }
  // 表格列配置：新增“进度”按钮（在“审核”后）
  const columns = [
    {
      title: '序号',
      dataIndex: 'serialNumber',
      key: 'serialNumber',
      width: "10%",
      align: 'center',
      render: (_: any, __: any, index: number) => index + 1,
    },
    {
      title: '企业名称',
      dataIndex: 'companyName',
      key: 'companyName',
      width: "15%",
      ellipsis: true,

    },
    {
      title: '联系人',
      dataIndex: 'concatPerson',
      key: 'concatPerson',
      width: "15%",
      ellipsis: true,

    },
    {
      title: '联系电话',
      dataIndex: 'concatPhone',
      key: 'concatPhone',
      width: "15%",
      ellipsis: true,

    },
    // {
    //   title: '环节',
    //   dataIndex: 'link',
    //   key: 'link',
    //   width: "10%",
    //   align: 'center',
    //   ellipsis: true,

    // },
    {
      title: '状态',
      dataIndex: 'auditStatus',
      key: 'auditStatus',
      width: "15%",
      align: 'center',
      ellipsis: true,
      render: (status: string) => getStatusTag(status),
    },
    {
      title: '操作',
      key: 'operation',
      width: "25%",// 加宽操作列容纳4个按钮
      align: 'center',
      render: (_: any, record: any) => (
        <Space size={2}>
          <Popconfirm title="是否删除" onConfirm={() => handleDelete(record.id)}>
            <Button
              type="primary"
              size="small"
              icon={<DeleteOutlined />}
              disabled
            >
              删除
            </Button>
          </Popconfirm>

          <Button
            type="primary"
            size="small"
            icon={<EditOutlined />}
            disabled={(() => {
              if(initialState?.currentUser.data.userType == "county"){
                return record.resultStatus != "待县（市、区）经商局审核"
              }
              if(initialState?.currentUser.data.userType == "city"){
                return record.resultStatus != "待市经信局审核"
              }
              return false
            })()}
            onClick={() => handleEdit(record, "编辑企业信息")}
          >
            编辑
          </Button>
          <Button
            type="primary"
            size="small"
            icon={<AuditOutlined />}
            disabled={(() => {
              if(initialState?.currentUser.data.userType == "county"){
                return record.resultStatus != "待县（市、区）经商局审核"
              }
              if(initialState?.currentUser.data.userType == "city"){
                return record.resultStatus != "待市经信局审核"
              }
              return false
            })()}
            onClick={() => handleEdit(record, "企业审核")}
          >
            {
              (() => {
              if(initialState?.currentUser.data.userType == "county" && record.resultStatus == "待县（市、区）经商局审核"){
                return "审核"
              }
              if(initialState?.currentUser.data.userType == "city" && record.resultStatus == "待市经信局审核"){
                return "审核"
              }
              return "已审核"
            })()
            }
          </Button>
          {/* 新增：进度按钮（所有状态可点击，统一蓝色样式） */}
          {/* <Button
            type="primary"
            size="small"
            icon={<ClockCircleOutlined />}
            // disabled={record.auditStatus == 'pending'}
            onClick={() => handleProgressOpen(record)}
          >
            进度
          </Button> */}
        </Space>
      ),
    },
  ];
  function addSelectableToNonLeafNodes(data: any[]) {
    data.forEach((node: { children: string | any[]; selectable: boolean }) => {
      if (node.children && node.children.length > 0) {
        node.selectable = false;
        addSelectableToNonLeafNodes(node.children as any[]);
      }
    });
    return data;
  }

  return (
    <div className="pilot-enterprise-management" style={{ padding: '20px' }}>
      <div
        style={{
          fontSize: 16,
          fontWeight: 500,
          color: '#1f2937',
          marginBottom: 12,
        }}
      >
        企业注册管理
      </div>

      {/* 搜索栏 */}
      <Card style={{ marginBottom: 16 }}>
        <Form form={searchForm} layout="inline" onFinish={handleSearch}>
          <Form.Item name="enterpriseName" label="企业名称">
            <Input allowClear placeholder="请输入企业名称" style={{ width: 200 }} />
          </Form.Item>
          <Form.Item name="auditStatus" label="状态">
            <Select allowClear placeholder="请选择状态" style={{ width: 160 }}>
              {STATUS_OPTIONS.map((option) => (
                <Option key={option.value} value={option.value}>
                  {option.label}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              搜索
            </Button>
          </Form.Item>
          <Form.Item>
            <Button onClick={handleReset} icon={<UndoOutlined />}>
              重置
            </Button>
          </Form.Item>
        </Form>
      </Card>

      <Card
        style={{
          borderRadius: 12,
          boxShadow: '0 2px 8px rgba(0,0,0,0.06)',
          // height: 'calc(100vh - 170px)', // 精确高度，保证内部滚动
          // overflowY: 'auto', // 内部滚动
          padding: '24px',
        }}
      >
        {/* 企业列表 */}
        <Table
          columns={columns as any}
          dataSource={enterprises}
          rowKey="id"
          pagination={{
            pageSize: pageProps.pageSize,
            current: pageProps.current, total: pageProps.total, showSizeChanger: true,
            onChange: usersPageOnchange
          }}
          bordered
          scroll={{ y: 'calc(100vh - 450px)' }}
          locale={{ emptyText: '暂无试点企业数据' }}
        />
      </Card>
      <CompanyAllInfosPage searchCallFun={handleSearch} />

      {/* ---------------------- 新增：企业办理进度弹窗 ---------------------- */}
      <Modal
        title={`${currentEnterprise?.enterpriseName || '企业'}注册办理进度`}
        open={modalVisible.progress}
        onCancel={() => setModalVisible({ ...modalVisible, progress: false })}
        maskClosable={false}
        width={900}
        footer={[
          <Button key="close" onClick={() => setModalVisible({ ...modalVisible, progress: false })}>
            关闭
          </Button>,
        ]}
        bodyStyle={{ maxHeight: '70vh', overflow: 'auto' }}
      >
        <Card bordered={false}>
          <Table
            className="custom-table"
            columns={progressColumns as any}
            dataSource={currentProgressList}
            rowKey="id"
            pagination={false} // 进度列表完整展示，不分页
            bordered
            locale={{ emptyText: '暂无该企业的注册办理进度记录' }}
            rowClassName={() => 'hover:bg-gray-50'} // 行悬浮高亮，提升交互体验
          />
        </Card>
      </Modal>
    </div>
  );
};

export default PilotEnterpriseManagement;
